package com.netty.utils;

import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.swing.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class PrintUtils {
    public static void main(String[] args) {
        FileInputStream textStream = null;
        try {
            textStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\打印订单1.png");
            if (textStream != null) {
                // 当打印内容不为空时
                HashPrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
                // 指定打印输出格式
                DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
                PrintService printServiceArr[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
                if (printServiceArr.length > 0) {
                    for (PrintService printService : printServiceArr) {
                        if (printService.getName().contains("FinePrint")) {
                            DocPrintJob job = printService.createPrintJob();
                            pras.add(MediaSizeName.ISO_A4);
                            DocAttributeSet das = new HashDocAttributeSet();
                            Doc doc = new SimpleDoc(textStream, flavor, das);
                            try {
                                job.print(doc, pras);
                            } catch (PrintException pe) {
                                pe.printStackTrace();
                            }
                        }
                    }
                } else {
                    System.out.println("找不到任何打印机");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
